package cn.pegasus.teamwork.appinterface.controller.washer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import cn.iyizhan.teamwork.base.util.ObjectUtil;
import cn.iyizhan.teamwork.base.util.PageObject;
import cn.pegasus.teamwork.appinterface.base.BaseController;
import cn.pegasus.teamwork.appinterface.controller.washer.vo.ReturnOrderVo;
import cn.pegasus.teamwork.appinterface.util.DateUtils;
import cn.pegasus.teamwork.appinterface.util.ParameterEunm;
import cn.pegasus.teamwork.appinterface.util.ReturnRsUtils;
import cn.pegasus.teamwork.pegasus.entity.BussServiceProject;
import cn.pegasus.teamwork.pegasus.entity.BussUserComment;
import cn.pegasus.teamwork.pegasus.entity.BussUserOrder;
import cn.pegasus.teamwork.pegasus.service.BussServiceProjectService;
import cn.pegasus.teamwork.pegasus.service.BussUcenterAreaService;
import cn.pegasus.teamwork.pegasus.service.BussUserCommentService;
import cn.pegasus.teamwork.pegasus.service.BussUserOrderService;
import cn.pegasus.teamwork.pegasus.service.BussWasherDepositService;
import cn.pegasus.teamwork.sysconfig.service.SysConfigMessageService;
import cn.pegasus.teamwork.sysconfig.service.SysConfigSmsService;
import cn.pegasus.teamwork.util.DateCompareUtil;

/**
 * @ClassorderName: SysUcenerUserController
 * @Description: 用户控制中心
 * @author ryan.bian
 * @date 2017年11月12日 上午10:10:32
 * 
 *       包括以下主要几个接口：
 * 
 *       =================================
 * 
 *       1.用户购买套餐 2.用户创建定单 3.用户充值 4.用户评价 5.用户打赏 6.用户订单列表查询 7.用户退单 - RefundVo
 *       8.获取用户定位地址后的小区列表（方圆 500 米）- VillageVo 9.订单详情
 * 
 *       ===========================================
 * 
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@Controller
@RequestMapping("/word/*")
public class WasherOrderController extends BaseController {

	private static final Logger LOGGER = LoggerFactory.getLogger(WasherOrderController.class);

	/**
	 * service
	 */
	@Autowired
	private BussUserOrderService bussUserOrderService;

	@Autowired
	private BussUserCommentService commentService;

	@Autowired
	private SysConfigSmsService configSmsService;

	@Autowired
	private BussWasherDepositService washerDepositService;

	@Autowired
	private BussServiceProjectService projectService;

	@Autowired
	private BussUcenterAreaService ucenterAreaService;
	
	@Autowired
	private SysConfigMessageService messageService;

	/**
	 * 用户订单列表查询
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/ols", method = RequestMethod.POST)
	public Map<String, Object> orderLists(HttpServletRequest request, HttpServletResponse respons,
			@RequestParam Map<String, Object> map) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 是否为空参数校验
		// 订单状态(1-未开始；2-开始服务；3-服务完成；10-订单取消；20-订单退款;30-已结算)
		map.put("washerId", getSessionWasherId());
		if (map.get("pageData") == null) {
			map.put("pageData", 10);
		}
		if (map.get("curPage") == null) {
			map.put("curPage", 1);
		}

		// 洗车工（0- 全部；1-待服务；2-服务中；3-已完成；10-已取消；20-退款审批;21-已退款）

		if (map.get("orderStatus") != null && Integer.valueOf(map.get("orderStatus").toString()) == 0) {
			map.put("orderStatus", null);
		} else if (map.get("orderStatus") != null && Integer.valueOf(map.get("orderStatus").toString()) == 1) {
			map.put("orderStatus", 1);
			map.put("payStatus", 2);
		} else if (map.get("orderStatus") != null && Integer.valueOf(map.get("orderStatus").toString()) == 2) {
			map.put("orderStatus", 2);
			map.put("payStatus", 2);
		} else if (map.get("orderStatus") != null && Integer.valueOf(map.get("orderStatus").toString()) == 3) {
			map.put("orderStatus", 3);
			map.put("payStatus", 2);
		} else if (map.get("orderStatus") != null && Integer.valueOf(map.get("orderStatus").toString()) == 10) {
			map.put("orderStatus", 10);
			map.put("payStatus", 2);
		} else if (map.get("orderStatus") != null && Integer.valueOf(map.get("orderStatus").toString()) == 20) {
			map.put("orderStatus", 20);
			map.put("payStatus", 2);
		} else if (map.get("orderStatus") != null && Integer.valueOf(map.get("orderStatus").toString()) == 21) {
			map.put("orderStatus", 21);
			map.put("payStatus", 2);
		}

		if (map.get("orderStatus") != null && Integer.valueOf(map.get("orderStatus").toString()) == 3) {
		}

		PageObject<BussUserOrder> newuses = bussUserOrderService.PageList(map);
		if (newuses != null) {
			// 考虑将小区信息后期放入缓存
			List<BussUserOrder> lis = newuses.getDataList();
			List<ReturnOrderVo> vos = new ArrayList<ReturnOrderVo>();
			if (lis != null && lis.size() > 0) {
				for (BussUserOrder bo : lis) {
					ReturnOrderVo vo = new ReturnOrderVo();
					String projectId = bo.getProjectId();
					String prpjectName = projectService.findProjectName(Long.valueOf(projectId));
					if (!StringUtils.isEmpty(prpjectName)) {
						vo.setProjectName(prpjectName);
					} else {
						vo.setProjectName("");
					}
					vo.setId(bo.getId().toString());
					vo.setUserId(bo.getUserId().toString());

					vo.setOrderNo(bo.getOrderNo());// 订单流水号
					vo.setOrderBalance(bo.getOrderBalance().toString());// 金额
					vo.setAreaAddress(bo.getAreaName() + bo.getAreaAddress());
					vo.setCarCode(bo.getCarCode()); // 车牌号
					vo.setCarBrand(bo.getCarBrand());
					// 车辆品牌
					vo.setCarColor(bo.getCarColor());
					// 车辆颜色
					vo.setCarImages(bo.getCarImages());
					// 车辆图片
					vo.setBespokeTime(bo.getBespokeBeginTime() + "-" + bo.getBespokeEndTime());
					vo.setLinkMan(bo.getLinkMan());
					// 联系人
					vo.setLinkTel(bo.getLinkTel());
					// 联系电话
					vo.setOrderStatus(bo.getOrderStatus().toString());
					// 订单状态(1-未开始；2-开始服务；3-服务完成；10-订单取消；20-申请退款;21-完成退款；30-已结算)
					vo.setCreateTime(bo.getCreateTime());
					;// 订单创建时间
					vo.setPayStatus(bo.getPayStatus());
					vo.setRechargeType(bo.getRechargeType()); // 方式（1-微信支付；2-余额支付）
					vo.setOrderIsevaluate(bo.getOrderIsevaluate()); // 是否评价(1-是；2-否)
					vo.setOrderIsreward(bo.getOrderIsreward()); // 是否打赏(1-是；2-否)
					vo.setExamineStatus(bo.getExamineStatus());// 退款申请审核（系统管理员）（0-不用审核；1-等待审核；2-通过；3-不通过）

					vos.add(vo);
				}
			}

			Map<String, Object> mape = new HashMap<String, Object>();
			Map<String, Object> tmape = new HashMap<String, Object>();
			tmape.put("dataList", vos);
			tmape.put("pageData", newuses.getPageData());
			tmape.put("totalData", newuses.getTotalData());
			tmape.put("endPage", newuses.getEndPage());
			tmape.put("curPage", newuses.getCurPage());
			tmape.put("totalPage", newuses.getTotalPage());
			mape.put("lis", tmape);
			resultMap = ReturnRsUtils.resultBackString(ParameterEunm.SUCCESSFUL_CODE, mape);
		} else {
			resultMap = ReturnRsUtils.resultBackString(ParameterEunm.ERROR_NULL_RESULT_CODE, null);
		}

		return resultMap;
	}

	/**
	 * 用户订单列表查询
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/nfc", method = RequestMethod.POST)
	public Map<String, Object> notFinishCount(HttpServletRequest request, HttpServletResponse respons,
			@RequestParam Map<String, Object> map) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 是否为空参数校验
		// 订单状态(1-未开始；2-开始服务；3-服务完成；10-订单取消；20-订单退款;30-已结算)
		map.put("payStatus", 2);
		map.put("orderStatus", 1);
		map.put("washerId", getSessionWasherId());
		List<BussUserOrder> newuses = bussUserOrderService.query(map);
		if (newuses != null && newuses.size() > 0) {
			// 考虑将小区信息后期放入缓存
			Map<String, Object> mape = new HashMap<String, Object>();
			mape.put("count", newuses.size());
			resultMap = ReturnRsUtils.resultBackString(ParameterEunm.SUCCESSFUL_CODE, mape);
		} else {
			resultMap = ReturnRsUtils.resultBackString(ParameterEunm.ERROR_NULL_RESULT_CODE, null);
		}

		return resultMap;
	}

	/**
	 * 开始服务
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/bs", method = RequestMethod.POST)
	public Map<String, Object> beginService(HttpServletRequest request, HttpServletResponse respons,
			@RequestParam Map<String, Object> map) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			// 是否为空参数校验,洗车之前的照片参数
			boolean isNotNull = ObjectUtil.checkObjectFile(new String[] { "id", "orderBeginimages" }, map);
			if (isNotNull) {
				Map<String, Object> tMap = new HashMap<String, Object>();
				tMap.put("id", map.get("id"));
				BussUserOrder bo = bussUserOrderService.detail(tMap);
				if (bo != null) {
					if (DateCompareUtil.isToday(bo.getBespokeBeginTime())) {
						long washerId = getSessionWasherId();

						// 此处判断该洗车工时否存正还没有结束的车辆
						Map<String, Object> tmap = new HashMap<String, Object>();
						tmap.put("washerId", washerId);
						tmap.put("orderIsassign", 1);
						tmap.put("orderStatus", 2);
						List<BussUserOrder> bos = bussUserOrderService.query(tmap);
						if (bos != null && bos.size() > 0) {
							resultMap = ReturnRsUtils.resultBackString(ParameterEunm.ERROR_WASHER_BEGINSERVICE_CODE,
									false);
						} else {
							// 如果有，则不能进行下一个订单的开始，如果没有，则进行订单开始
							if (washerId > 0 && (bo.getPayStatus() == 2) && (washerId == bo.getWasherId())
									&& (bo.getOrderStatus() == 1)) {
								bo.setOrderStatus(2); // 订单状态(1-未开始；2-开始服务；3-服务完成；10-订单取消；20-订单退款;30-已结算)
								// bo.setBespokeBeginTime(DateUtils.getNowDate());
								bo.setOrderBeginTime(DateUtils.getNowDate());
								bo.setOrderBeginimages(map.get("orderBeginimages").toString());
								bussUserOrderService.update(bo);
								// 发送短信通知，用户退单
								String projectId = bo.getProjectId();
								BussServiceProject p = projectService.findProjectInfo(Long.valueOf(projectId));
								if( p != null ){
									String times = p.getProjectTimes();
									try {
										configSmsService.sendBeginServiceNotice(bo.getLinkTel(),
												bo.getLinkMan(), bo.getCarCode(),times+"分钟");
										messageService.addMessage(1,"2", "开始服务通知", "尊敬的 " + bo.getLinkMan()
										+"，您的爱车" + bo.getCarCode() +"，已开始洗车服务，服务时间"+ times+"分钟"+"，谢谢！",
										bo.getUserId().toString());
									} catch (Exception e) {
										LOGGER.error("订单支付-微信支付发送站内信息或者短信失败，订单号为 ： " + bo.getOrderNo());
									}
								}
								resultMap = ReturnRsUtils.resultBackString(ParameterEunm.SUCCESSFUL_CODE, true);
							} else {
								resultMap = ReturnRsUtils.resultBackString(ParameterEunm.ERROR_WASHER_PARAMS_CODE,
										false);
							}
						}
					} else {
						resultMap = ReturnRsUtils.resultBackString(ParameterEunm.ERROR_BEGIN_SERVICE_ORDER_NOTFIND,null);
					}
					
				} else {
					resultMap = ReturnRsUtils.resultBackString(ParameterEunm.ERROR_NULL_RESULT_CODE, false);
				}
			} else {
				resultMap = ReturnRsUtils.resultBackString(ParameterEunm.ERROR_NULL_RESULT_CODE, false);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultMap;
	}

	/**
	 * 结束服务
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/es", method = RequestMethod.POST)
	public Map<String, Object> endService(HttpServletRequest request, HttpServletResponse respons,
			@RequestParam Map<String, Object> map) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			// 是否为空参数校验 洗车之后的照片参数
			boolean isNotNull = ObjectUtil.checkObjectFile(new String[] { "id", "orderEndimages" }, map);
			if (isNotNull) {
				Map<String, Object> tMap = new HashMap<String, Object>();
				tMap.put("id", map.get("id"));
				BussUserOrder bo = bussUserOrderService.detail(tMap);
				if (bo != null) {
					long id = getSessionWasherId();

					String projectId = bo.getProjectId();
					BussServiceProject bsp = projectService.findProjectInfo(Long.valueOf(projectId));
					// 此处判断该洗车工时否存正还没有结束的车辆
					// 此处从数据字典里面获取值，暂时写定 30 分钟
					long times = Integer.valueOf(bsp.getProjectTimes()) * 60 * 1000;
					if (id > 0 && (bo.getPayStatus() == 2) && (id == bo.getWasherId()) && (bo.getOrderStatus() == 2)) {
						// 如果有，则不能进行下一个订单的开始，如果没有，则进行订单开始
						if ((bo.getOrderBeginTime().getTime()) + times <= System.currentTimeMillis()) {
							bo.setOrderStatus(3); // 订单状态(1-未开始；2-开始服务；3-服务完成；10-订单取消；20-订单退款;30-已结算)
							bo.setBespokeEndTime(DateUtils.getNowDate());
							bo.setOrderEndimages(map.get("orderEndimages").toString());
							if (map.get("washerLeaveMsg") != null) {
								bo.setWasherLeaveMsg(map.get("washerLeaveMsg").toString());
							}
							bussUserOrderService.update(bo);

							// 洗车工完成服务订单时候，资金变化
							bussUserOrderService.finishServiceMoney(bo);

							try {
								// 发送短信通知，用户退单
								configSmsService.sendSerNotice(bo.getLinkTel(), bo.getCarCode());
								messageService.addMessage(1,"2", "结束服务通知", "尊敬的 " + bo.getLinkMan()
								+"，您的爱车" + bo.getCarCode() +"，已经服务完毕，请您安全驾驶，谢谢！",
								bo.getUserId().toString());
							} catch (Exception e) {
								LOGGER.error("订单支付-微信支付发送站内信息或者短信失败，订单号为 ： " + bo.getOrderNo());
							}

							resultMap = ReturnRsUtils.resultBackString(ParameterEunm.SUCCESSFUL_CODE, true);
						} else {
							resultMap = ReturnRsUtils.resultBackString(ParameterEunm.ERROR_WASHER_ENDSERVICE_CODE,
									false);
						}
					} else {
						resultMap = ReturnRsUtils.resultBackString(ParameterEunm.FAILED_CODE, false);
					}
				} else {
					resultMap = ReturnRsUtils.resultBackString(ParameterEunm.ERROR_NULL_RESULT_CODE, false);
				}
			} else {
				resultMap = ReturnRsUtils.resultBackString(ParameterEunm.ERROR_NULL_RESULT_CODE, false);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultMap;
	}

	/**
	 * 用户评价
	 * 
	 * @param phone_number
	 * @param app_code
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/ct", method = RequestMethod.POST)
	public Map<String, Object> comment(HttpServletRequest request, HttpServletResponse respons,
			@RequestParam Map<String, Object> map) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			boolean isNotNull = ObjectUtil.checkObjectFile(new String[] { "orderId", "score", "descs" }, map);
			// images 、id，fid 不是必须字段
			// 1. 用户充值
			if (isNotNull) {
				BussUserComment bus = new BussUserComment();
				bus.setUserId(getSessionWasherId());
				bus.setOrderId(Integer.valueOf(map.get("orderId").toString()));
				bus.setScore(Integer.valueOf(map.get("score").toString()));
				bus.setDescs(map.get("descs").toString());
				if (map.get("images") != null) {
					bus.setImages(map.get("images").toString());
				}

				if (map.get("fid") != null) {
					bus.setFid(Integer.valueOf(map.get("fid").toString()));
				}
				bus.setCreateUserId(getSessionWasherId());
				bus.setCreateTime(DateUtils.getNowDate());

				BussUserComment cbus = commentService.add(bus);
				if (cbus != null) {
					// 更新订单状态：
					int id = Integer.valueOf(map.get("orderId").toString());
					Map<String, Object> tMap = new HashMap<String, Object>();
					tMap.put("id", id);
					BussUserOrder bo = bussUserOrderService.detail(tMap);
					if (bo != null) {
						bo.setOrderIsevaluate(1);
						bussUserOrderService.update(bo);
					}

					resultMap = ReturnRsUtils.resultBackString(ParameterEunm.SUCCESSFUL_CODE, cbus);
				} else {
					resultMap = ReturnRsUtils.resultBackString(ParameterEunm.FAILED_CODE, null);
				}
			} else {
				resultMap = ReturnRsUtils.resultBackString(ParameterEunm.ERROR_BANK_PARAMS_CODE, null);
			}

		} catch (Exception e) {
			LOGGER.error("验证手机号码失败.", e);
			resultMap = ReturnRsUtils.resultBackString(ParameterEunm.FAILED_CODE, null);
		}
		LOGGER.info("返回参数 ：{}", JSONObject.toJSON(resultMap));
		return resultMap;
	}

	/**
	 * 用户退单审核（同意退款）
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/rfs", method = RequestMethod.POST)
	public Map<String, Object> refunds(HttpServletRequest request, HttpServletResponse respons,
			@RequestParam Map<String, Object> map) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 订单状态(1-未开始；2-开始服务；3-服务完成；10-订单取消；20-申请退款;21-完成退款；30-已结算)
		try {
			boolean isNotNull = ObjectUtil.checkObjectFile(new String[] { "orderId" }, map);
			if (isNotNull) {
				long washerId = getSessionWasherId();
				map.put("washerId", washerId);
				map.put("orderStatus", 20);
				boolean rs = bussUserOrderService.washerProessRefunds(map);
				if (rs) {
					resultMap = ReturnRsUtils.resultBackString(ParameterEunm.SUCCESSFUL_CODE, true);
				} else {
					resultMap = ReturnRsUtils.resultBackString(ParameterEunm.FAILED_CODE, false);
				}

			} else {
				resultMap = ReturnRsUtils.resultBackString(ParameterEunm.ERROR_PARAMS_CODE, null);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultMap;
	}

	/**
	 * 查询订单详情
	 * 
	 * @param request
	 * @param respons
	 * @param map
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/oi", method = RequestMethod.POST)
	public Map<String, Object> orderInfo(HttpServletRequest request, HttpServletResponse respons,
			@RequestParam Map<String, Object> map) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 是否为空参数校验
		boolean isNotNull = ObjectUtil.checkObjectFile(new String[] { "id" }, map);
		if (isNotNull) {
			Map<String, Object> rmaps = new HashMap<String, Object>();
			long washerId = getSessionWasherId();
			map.put("washerId", washerId);
			BussUserOrder newuses = bussUserOrderService.detail(map);
			if (newuses != null) {
				String projectId = newuses.getProjectId();
				Map<String, Object> tMap = new HashMap<String, Object>();
				tMap.put("id", projectId);

				BussServiceProject pro = projectService.detail(tMap);
				if (pro != null) {
					newuses.setProjectDesc(pro.getProjectDesc());
					newuses.setProjectName(pro.getProjectName());
				}
				int areaId = newuses.getAreaId();
				String name = ucenterAreaService.getAreaName(areaId);
				newuses.setAreaAddress(name + newuses.getAreaAddress());

				// 查询订单评论信息
				// Map<String, Object> rMap = new HashMap<String, Object>();
				// rMap.put("orderId", newuses.getId());
				// BussUserComment cbus = commentService.detail(rMap);
				// if(cbus != null ){
				// rmaps.put("comment", cbus);
				// }
				// rmaps.put("order", newuses);

				resultMap = ReturnRsUtils.resultBackString(ParameterEunm.SUCCESSFUL_CODE, newuses);
			} else {
				resultMap = ReturnRsUtils.resultBackString(ParameterEunm.ERROR_NULL_RESULT_CODE, null);
			}
		} else {
			resultMap = ReturnRsUtils.resultBackString(ParameterEunm.ERROR_PARAMS_CODE, null);
		}
		return resultMap;
	}

	/**
	 * 洗车工缴纳押金
	 * 
	 * @param id
	 * @param map
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/cwdo", method = RequestMethod.POST)
	public Map<String, Object> createWasherDepositOrder(HttpServletRequest request, HttpServletResponse respons,
			@RequestParam Map<String, Object> map) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			boolean isNotNull = ObjectUtil.checkObjectFile(new String[] { "orderBalance", "openid", "type" }, map);
			// 1. 用户充值
			if (isNotNull) {
				int washerId = Integer.valueOf(getSessionWasherId().toString());
				map.put("washerId", washerId);
				if (Integer.valueOf(map.get("type").toString()) == 1) {
					// 中间的参数的是 微信支付
					Map<String, Object> tMap = washerDepositService.createWasherDepositOrder(map, 1, 1);
					if (tMap != null) {
						resultMap = ReturnRsUtils.resultBackString(ParameterEunm.SUCCESSFUL_CODE, tMap);
					} else {
						resultMap = ReturnRsUtils.resultBackString(ParameterEunm.ERROR_NULL_RESULT_CODE, null);
					}
				} else if (Integer.valueOf(map.get("type").toString()) == 2) {
					// TODO APP充值再定
					Map<String, Object> tMap = new HashMap<String, Object>();
					if (tMap != null) {
						// 2. 对于用户充值后，对资金进行补充

						resultMap = ReturnRsUtils.resultBackString(ParameterEunm.SUCCESSFUL_CODE, tMap);
					}
				}

			} else {
				resultMap = ReturnRsUtils.resultBackString(ParameterEunm.ERROR_PARAMS_CODE, null);
			}

		} catch (Exception e) {
			LOGGER.error("修改用户失败.", e);
			resultMap = ReturnRsUtils.resultBackString(ParameterEunm.FAILED_CODE, null);
		}
		LOGGER.info("返回参数 ：{}", JSONObject.toJSON(resultMap));
		return resultMap;
	}

}
